//
//  UITextView + emoticons.swift
//  02-表情
//
//  Created by 张宏芝 on 15/9/15.
//  Copyright © 2015年 kama. All rights reserved.
//

import Foundation

import UIKit

extension UITextView{
    
/// 返回完整的表情字符串
    // 计算型属性
    var emoticonText: String{
        
        let attText = attributedText
        var strM = String()
        
        attText.enumerateAttributesInRange(NSRange(location: 0, length: attText.length), options: []) { (dict, range, _) -> Void in
//            如果字典中包含NSAttachment  key说明是图片
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment{
                print("表情图片")
                strM += attachment.chs!
            }else{
                let str = (attText.string as NSString).substringWithRange(range)
                print("文本内容:\(str)")
                strM += str
            }
        }
        print("最终结果\(strM)")
        return strM
    }
    
    
///   插入表情符号
    func insertEmoticon(emoticon:Emoticon){
        //        0.
        //        1.删除按钮
        if emoticon.isRemove{
            deleteBackward()
            return
        }
        //        2.emoji
        if emoticon.emoji != nil{
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        //        3.表情图片--一定有图片
        let imageText = EmoticonAttachment.emoticonAttributeText(emoticon, font: font!)
        
        //        1>从中取出属性文本
        let strM = NSMutableAttributedString(attributedString: attributedText)
        //        2>插入图片文字
        strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
        
        //        3>重新设置的内容
        // 1)记住光标的位置
        let range = selectedRange
        // 2)设置内容
        attributedText = strM
        // 3)恢复光标位置
        selectedRange = NSRange(location: range.location + 1, length: 0)
        // 4)执行代理
        delegate?.textViewDidChange!(self)
    }
    
}
